package xworker.netty.handlers.http;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import xworker.lang.task.TaskManager;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class HttpSessionManager {	
	private static final Map<String, HttpSession> sessions = new ConcurrentHashMap<>();
	static{
		TaskManager.getScheduledExecutorService().scheduleAtFixedRate(HttpSessionManager::checkExpiredSession, 0, 1000, TimeUnit.MILLISECONDS);
	}

	private static void checkExpiredSession(){
		try {
			for (String key : sessions.keySet()) {
				HttpSession session = sessions.get(key);
				if(session == null || session.isExpired()){
					sessions.remove(key);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private static int sessionExpireTime = 900;

	/**
	 * 会话超时事件，单位秒。
	 */
	public static int getSessionExpireTime() {
		return sessionExpireTime;
	}

	/**
	 * 设置会话超时事件，单位秒。
	 *
	 * @param sessionExpireTime 会话超时时间，单位秒
	 */
	public static void setSessionExpireTime(int sessionExpireTime) {
		HttpSessionManager.sessionExpireTime = sessionExpireTime;
	}

	public static HttpSession getHttpSession(ChannelHandlerContext ctx, FullHttpRequest request, RequestBean requestBean) {
		String sessionId = requestBean.getCookieValue(HttpSession.SESSIONID);
		HttpSession httpSession = null;
		if(sessionId != null) {
			httpSession = sessions.get(sessionId);
		}
		
		if(httpSession != null && httpSession.isExpired()) {
			httpSession = null;
		}
		
		if(httpSession == null) {
			sessionId = UUID.randomUUID().toString();
			httpSession = new HttpSession(sessionId);
			sessions.put(sessionId, httpSession);
		}
		
		httpSession.active();

		requestBean.session = httpSession;
		return httpSession;		
	}
}
